//
//  CrashHandler.swift
//  CrashHandlerTest
//
//  Created by WangJensen on 6/30/17.
//  Copyright © 2017 WangJensen. All rights reserved.
//

import Foundation

public typealias Completion = ()->Void;
public typealias CrashCallback = (String,Completion)->Void;

public var crashCallBack: CrashCallback? = nil

private func signalHandler(signal:Int32) -> Void {
    let stackTrace = Thread.callStackSymbols.joined(separator: "\r\n")
    crashCallBack?(stackTrace,{
        unregisterSignalHandler();
        exit(signal);
    });
}

private func registerSignalHanlder()
{
    objc_setUncaughtExceptionHandler { (_response:Any?) in
        if let signal = _response as? Int32 {
            signalHandler(signal: signal)
        }
        else if let exception = _response as? NSException {
            print("++++++++++++++++++ 异常信息 ++++++++++++++++++")
            NSLog("name:%@",exception.name.rawValue)
            NSLog("reason:%@",exception.reason ?? "--")
            NSLog("userInfo:%@",exception.userInfo ?? [:])
            NSLog("Stack Trace:%@",exception.callStackSymbols)
            NSLog("Stack ReturnAddresses:\n%@", exception.callStackReturnAddresses)
            NSLog("Exception All:\n%@", exception)
            
            crashCallBack?(exception.debugDescription,{
                unregisterSignalHandler();
                exception.raise();
            });
        }
    }
    
    signal(SIGINT,  signalHandler);
    signal(SIGSEGV, signalHandler);//野指针，僵尸对象
    signal(SIGTRAP, signalHandler);
    signal(SIGABRT, signalHandler);
    signal(SIGILL,  signalHandler);
    signal(SIGBUS,  signalHandler);
    signal(SIGFPE,  signalHandler);
    signal(SIGTERM, signalHandler);
    signal(SIGKILL, signalHandler);//CPU无法执行的代码(比如无效指令、除以0等)
    signal(SIGPIPE, signalHandler);
}

private func unregisterSignalHandler()
{
    signal(SIGINT,  SIG_DFL);
    signal(SIGSEGV, SIG_DFL);
    signal(SIGTRAP, SIG_DFL);
    signal(SIGABRT, SIG_DFL);
    signal(SIGILL,  SIG_DFL);
    signal(SIGBUS,  SIG_DFL);
    signal(SIGFPE,  SIG_DFL);
    signal(SIGTERM, SIG_DFL);
    signal(SIGKILL, SIG_DFL);
    signal(SIGPIPE, SIG_DFL);
}

public class CrashHandler
{
    public static func setup(callBack:@escaping CrashCallback){
        crashCallBack = callBack;
        registerSignalHanlder();
    }
}
